<script setup lang="ts">
import { ElButton } from 'element-plus'
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import * as echarts from 'echarts'
import { ElMessageBox } from 'element-plus';

const route = useRoute()
const routerInstance = useRouter()
const chartRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

// 接收上传页传递的参数
const leftEyeImageUrl = ref(route.params.leftEyeImageUrl as string || '')
const rightEyeImageUrl = ref(route.params.rightEyeImageUrl as string || '')
const gender = ref(route.params.gender as string || '')
const age = ref(route.params.age as string || '')
const probabilities = ref(route.params.probabilities)

// 模拟预测数据（可替换为真实接口返回）
const predictionData = ref([
  { name: '白内障', value: 0.5 },
  { name: '糖尿病视网膜病变', value: 0.25 },
  { name: '青光眼', value: 0.1 },
  { name: '正常', value: 0.15 }
])

// 计算最大概率诊断结果
const diagnosisResult = computed(() => {
  const maxItem = predictionData.value.reduce(
    (prev, curr) => (prev.value > curr.value ? prev : curr),
    predictionData.value[0]
  );
  return `${maxItem.name} (${maxItem.name === '正常' ? 'Normal' : 'Abnormal'})`;
});

// 动态设置结果颜色
const resultColor = computed(() =>
  diagnosisResult.value.includes('正常') ? '#67C23A' : '#F56C6C'
);

// 图表初始化
onMounted(() => {
  console.log(probabilities.value)
  if (chartRef.value) {
    chart = echarts.init(chartRef.value)
    initChart()

    const handleResize = () => {
      chart?.resize()
    }
    window.addEventListener('resize', handleResize)

    onBeforeUnmount(() => {
      window.removeEventListener('resize', handleResize)
      chart?.dispose()
    })
  }
})

// 初始化图表配置
const initChart = () => {
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    xAxis: {
      type: 'value',
      axisLabel: { formatter: '{value}' }
    },
    yAxis: {
      type: 'category',
      data: predictionData.value.map(item => item.name)
    },
    series: [
      {
        name: '概率',
        type: 'bar',
        data: predictionData.value.map(item => item.value),
        itemStyle: {
          color: (params: { dataIndex: number }) => 
            params.dataIndex === 3 ? '#67C23A' : '#F56C6C'
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}'
        }
      }
    ]
  }
  chart?.setOption(option)
}

// 重新上传功能
const reupload = () => {
  ElMessageBox.confirm('确定要重新上传图片吗？')
    .then(() => {
      routerInstance.push('/upload');
    })
    .catch(() => {});
};
</script>

<template>
  <div class="result-container">
    <h1 class="gradient-title">眼部是否患病实时分类预测</h1>

    <!-- 上传信息概览 -->
    <div class="upload-summary">
      <div class="upload-item">
        <span class="label">左眼图像:</span>
        <div class="file-info">
          <span class="file-name">已上传左眼图像</span>
        </div>
      </div>
      <div class="upload-item">
        <span class="label">右眼图像:</span>
        <div class="file-info">
          <span class="file-name">已上传右眼图像</span>
        </div>
      </div>
      <div class="upload-item">
        <span class="label">性别:</span>
        <span class="value">{{ gender }}</span>
      </div>
      <div class="upload-item">
        <span class="label">年龄:</span>
        <span class="value">{{ age }}</span>
      </div>
      <el-button type="primary" @click="reupload">重新上传</el-button>
    </div>

    <!-- 结果内容区 -->
    <div class="result-content">
      <!-- 双眼预览区 -->
      <div class="image-section">
        <div class="image-wrapper" v-if="leftEyeImageUrl">
          <img :src="leftEyeImageUrl" alt="左眼图像" />
          <p class="image-label">左眼图像</p>
        </div>
        <div class="image-wrapper" v-if="rightEyeImageUrl" style="margin-left: 20px;">
          <img :src="rightEyeImageUrl" alt="右眼图像" />
          <p class="image-label">右眼图像</p>
        </div>
      </div>

      <!-- 诊断结果区 -->
      <div class="result-section">
        <h2 :style="{ color: resultColor }">预测结果: {{ diagnosisResult }}</h2>
        
        <h3>模型预测概率分布</h3>
        <div ref="chartRef" class="chart-container"></div>
        
        <div class="result-details">
          <div class="details-header">
            <h4>诊断建议:</h4>
            <span 
              class="status-tag" 
              :class="{ 'normal': diagnosisResult.includes('正常'), 'abnormal': !diagnosisResult.includes('正常') }"
            >
              {{ diagnosisResult.includes('正常') ? '正常' : '异常' }}
            </span>
          </div>
          <p v-if="diagnosisResult.includes('正常')">
            您的眼部状况正常，建议每年进行一次常规检查，重点关注眼压、眼底视网膜等基础项目。
          </p>
          <p v-else>
            检测到异常情况，建议 <strong>72 小时内</strong> 预约专业眼科医生，进行 OCT 断层扫描、视野检查等详细检测。
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.result-container {
  width: 1200px;
  max-width: 100%;
  margin: 5px auto;
  padding: 40px 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.gradient-title {
  font-size: 28px;
  margin-bottom: 35px;
  background: linear-gradient(90deg, #165DFF 0%, #36D399 100%);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  text-shadow: 0 2px 10px rgba(22, 93, 255, 0.1);
}

/* 上传信息概览 */
.upload-summary {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 30px;
  align-items: center;
}

.upload-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.label {
  font-size: 16px;
  color: #666;
  width: 80px;
  text-align: right;
}

.value, .file-name {
  font-size: 14px;
  color: #333;
}

/* 图片预览区 */
.result-content {
  display: flex;
  gap: 40px;
  align-items: flex-start;
  width: 100%;
}

.image-section {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.image-wrapper {
  width: 360px;
  min-height: 360px;
  border: 1px dashed #ddd;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #fcfcfc;
  padding: 20px;
  box-sizing: border-box;
}

.image-wrapper img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.image-label {
  margin-top: 10px;
  color: #999;
  font-size: 14px;
}

/* 诊断结果区 */
.result-section {
  flex: 1;
}

h2 {
  font-size: 20px;
  margin-bottom: 20px;
}

h3 {
  font-size: 16px;
  color: #666;
  margin-bottom: 15px;
}

.chart-container {
  width: 100%;
  height: 300px;
  margin: 20px 0;
}

.result-details {
  margin-top: 30px;
  padding: 20px 24px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  font-size: 14px;
  line-height: 1.7;
  color: #555;
}

.details-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.details-header h4 {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.status-tag {
  margin-left: 8px;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-tag.normal {
  background-color: #e6f8e2;
  color: #4caf50; 
  border: 1px solid #d3eecf;
}

.status-tag.abnormal {
  background-color: #fff3f0;
  color: #f44336; 
  border: 1px solid #fadada;
}

.result-details p {
  margin: 0;
  text-indent: 2em;
}

.result-details p strong {
  color: #f44336;
  font-weight: 600;
}
</style>